package com.hq.fxh.No4_XiaoXi.IM;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hq.fxh.No0_ChengQu.Activity.BaseActivity;
import com.hq.fxh.R;
import com.hq.fxh.Utils.LogUtils;
import com.hq.fxh.Utils.Tool;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.content.MessageContent;
import cn.jpush.im.android.api.content.TextContent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.MessageSendingOptions;
import cn.jpush.im.api.BasicCallback;

public class LiaoTianActivity extends BaseActivity implements View.OnClickListener {

    protected ListView listMessage;
    protected EditText edit;
    protected Button button2;
    protected ImageView toolbarImageBack;
    protected LinearLayout toolbarLayoutBack;
    protected TextView toolBarTvTitle;
    protected TextView toolBarTvMore;
    protected LinearLayout toolbarLayoutMore;
    private String TAG = "我的信息";
    private Ladapte_LiaoTian mAdapter;
    private List<Message> mData;
    String toUser;
    Message message;

    @Override
    protected void initView() {
        listMessage = (ListView) findViewById(R.id.list_message);
        edit = (EditText) findViewById(R.id.edit);
        button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(LiaoTianActivity.this);
        mData = new ArrayList<Message>();
        mAdapter = new Ladapte_LiaoTian();
        mAdapter.setmData(mData);
        listMessage.setAdapter(mAdapter);
        toolbarImageBack = (ImageView) findViewById(R.id.toolbar_image_back);
        toolbarLayoutBack = (LinearLayout) findViewById(R.id.toolbar_Layout_back);
        toolbarLayoutBack.setOnClickListener(LiaoTianActivity.this);
        toolBarTvTitle = (TextView) findViewById(R.id.toolBar_tv_Title);
        toolBarTvMore = (TextView) findViewById(R.id.toolBar_tv_More);
        toolbarLayoutMore = (LinearLayout) findViewById(R.id.toolbar_Layout_More);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_message2;
    }

    @Override
    protected void initData() {
        JMessageClient.registerEventReceiver(this);
        toUser = getIntent().getStringExtra("user");
        isExistUser();

        initView();

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button2) {
            clickSent();
        } else if (view.getId() == R.id.toolbar_Layout_back) {
            finish();

        }
    }

    private void clickSent() {

        String text = edit.getText().toString();
        if (!TextUtils.isEmpty(toUser) && !TextUtils.isEmpty(text)) {
            String appkey = null;
            String customFromName = null;
            String extraKey = null;
            String extraValue = null;
            boolean retainOfflineMsg = true;
            boolean showNotification = true;
            boolean enableCustomNotify = false;

            //通过username和appkey拿到会话对象，通过指定appkey可以创建一个和跨应用用户的会话对象，从而实现跨应用的消息发送
            Conversation mConversation = JMessageClient.getSingleConversation(toUser, appkey);
            if (mConversation == null) {
                mConversation = Conversation.createSingleConversation(toUser, appkey);
            }

            //构造message content对象
            TextContent textContent = new TextContent(text);
            //设置自定义的extra参数
            textContent.setStringExtra(extraKey, extraValue);

            //创建message实体，设置消息发送回调。
            message = mConversation.createSendMessage(textContent, customFromName);
            message.setOnSendCompleteCallback(new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    if (i == 0) {
                        Toast.makeText(getApplicationContext(), "发送成功", Toast.LENGTH_SHORT).show();
                        mData.add(message);
                        notifi();

                    } else {
                        Log.i(TAG, "JMessageClient.createSingleTextMessage" + ", responseCode = " + i + " ; LoginDesc = " + s);
                        Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            //设置消息发送时的一些控制参数
            MessageSendingOptions options = new MessageSendingOptions();
            options.setRetainOffline(retainOfflineMsg);//是否当对方用户不在线时让后台服务区保存这条消息的离线消息
            options.setShowNotification(showNotification);//是否让对方展示sdk默认的通知栏通知
            options.setCustomNotificationEnabled(enableCustomNotify);//是否需要自定义对方收到这条消息时sdk默认展示的通知栏中的文字
            if (enableCustomNotify) {
                options.setNotificationTitle("薛文豪通知");//自定义对方收到消息时通知栏展示的title
                options.setNotificationAtPrefix("薛文豪 前缀");//自定义对方收到消息时通知栏展示的@信息的前缀
                options.setNotificationText("薛文豪 内容");//自定义对方收到消息时通知栏展示的text
            }

            //发送消息
            JMessageClient.sendMessage(message, options);
        } else {
            Toast.makeText(getApplicationContext(), "必填字段不能为空", Toast.LENGTH_SHORT).show();
        }
    }


    public void notifi() {


        LogUtils.e(" 线程名字 ： " + Thread.currentThread().getName());
        mAdapter.notifyDataSetChanged();
        listMessage.setSelection(mData.size() - 1);
        edit.setText("");
    }


    private void isExistUser() {
        UserInfo myInfo = JMessageClient.getMyInfo();
        if (myInfo == null) {
            LogUtils.startToash(this, "未获取到本人信息，请尝试从新登陆");
            finish();
        } else {
            testToUser();
        }
    }


    public void testToUser() {
        LogUtils.e("测试对方用户是否存在ID" + toUser);
        JMessageClient.getUserInfo(toUser + "", new GetUserInfoCallback() {

            @Override
            public void gotResult(int responseCode, String responseMessage, UserInfo info) {
                if (responseCode == 0) {
                    String nickname = info.getNickname();
                    if (nickname == null || nickname.equals("")) {
                        Tool.setStringToText(toolBarTvTitle, info.getUserName());
                    } else {
                        Tool.setStringToText(toolBarTvTitle, nickname);
                    }
                    JMessageClient.enterSingleConversation(toUser, null);
                    Conversation singleConversation = JMessageClient.getSingleConversation(toUser);
                    List<Message> allMessage = singleConversation.getAllMessage();
                    mData.addAll(allMessage);

                    notifi();
                } else {
                    LogUtils.startToash(LiaoTianActivity.this, "对方暂未激活该功能");
                    finish();
                }
            }
        });


    }

    public void onEvent(MessageEvent event) {
        Message msg = event.getMessage();

        MessageContent content = msg.getContent();
        UserInfo targetInfo = (UserInfo) msg.getTargetInfo();
        if (targetInfo.getUserName().equals(toUser)) {
            switch (msg.getContentType()) {
                case text:
                    TextContent textContent = (TextContent) content;
                    final String str = textContent.getText();
                    mData.add(msg);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            notifi();
                        }
                    });
                    break;
            }
        } else {

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JMessageClient.unRegisterEventReceiver(this);
    }


}
